package com.nf.dao;

import com.nf.entity.User;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.query.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
@Scope("prototype")
public class UserDaoImpl implements UserDao {

    @Autowired
    private SessionFactory sessionFactory = null;

    public void add(){
        /*每次创新一个新的Session，需要开启事务以及提交事务*/
        //Session session = sessionFactory.openSession();

        /*使用getCurrentSession方法就可以自动开启提交事务
        * 并保证与事务管理器使用同一个Session*/
        Session session = sessionFactory.getCurrentSession();

            User user = new User();
            user.setName("我不爱你");
            user.setSex("男");

            User user1 = new User();
            user1.setName("你的名字");
            user1.setSex("我");

            session.save(user);
            session.save(user1);

            //session.close();
    }

    public List<User> getAllUser() {
        List<User> userList = null;
        /*//spring将直接替代掉下面3行代码
        //Configuration configuration = new Configuration();
        //configuration.configure("hibernate.cfg.xml.bak");
        //factory = configuration.buildSessionFactory();*/

        Session session = sessionFactory.openSession();

        Query query = session.createQuery("from User u where u.id>:myid");

       /* 以下两句需要用到User.hbm.xml配置文件*/
        //Query query = session.createNamedQuery("selectUserById");
        //Query query = session.createNamedQuery("myQuery",User.class);

        query.setParameter("myid",1);
        userList = query.getResultList();

        for (User u:userList){
            System.out.println("id:"+u.getId());
        }

        session.close();
        //sessionFactory.close();

        System.out.println(userList+" 大小："+userList.size());

        return userList;
    }
}
